package GameDb.Task;

import GameDb.DbHandler;
import GameDb.JDBC.JDBCTemplate;
import GameDb.Task.common.DbTask;
import Protobuf.DbProto;
import Server.Common.Player;
import io.netty.channel.ChannelHandlerContext;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;


/**
 * @author jedi
 */
public class DbLogin implements DbTask {
    private final ChannelHandlerContext ctx;
    private final DbProto.Msg msg;
    String psd = "password";

    public DbLogin(ChannelHandlerContext ctx,DbProto.Msg msg){
        this.ctx = ctx;
        this.msg = msg;
    }

    @Override
    public void run(Connection conn) throws Exception {
        String username = msg.getLogin().getUsername();
        String psd = msg.getLogin().getPsd();
        String sql = "SELECT a.id,a.username,a.password,b.name,b.tid,b.guid FROM user AS a,player AS b WHERE a.username = ? AND a.id=b.id";
        JDBCTemplate jdbcTemplate = new JDBCTemplate();
        Map<String,Object> map = (Map<String,Object>)jdbcTemplate.selectDbOperate(conn,sql,3,username);
        dealDb(ctx,username,psd,map);
    }

    public void dealDb(ChannelHandlerContext ctx,String username, String password, Map<String,Object> map) {
        long id = 0;
        String clientChannelId = msg.getChannelId();
        Player player = new Player.Builder().setId(id).setUsername(username).build();
        if(map.size() != 0&&password.equals(map.get(psd))) {
            player.setId(Long.parseLong(map.get("id").toString()));
            player.setName((String)map.get("name"));
            player.setTid(Long.parseLong(map.get("id").toString()));
            player.setGuid(Long.parseLong(map.get("guid").toString()));
        }
        if(map.size() != 0&&!password.equals(map.get(psd))){
            player.setId(1L);
        }
        DbProto.Msg loginDbMsg = DbProto.Msg.newBuilder().setMsgType(DbProto.Msg.MsgType.logSuc).setChannelId(clientChannelId)
                .setPlayer(DbProto.Player.newBuilder().setId(player.getId()).setUsername(player.getUsername()).build()).build();
        if(password.equals(map.get(psd))){
            loginDbMsg = DbProto.Msg.newBuilder().setMsgType(DbProto.Msg.MsgType.logSuc).setChannelId(clientChannelId)
                    .setPlayer(DbProto.Player.newBuilder().setId(player.getId()).setName(player.getName()).setPsd(password)
                            .setTid(player.getTid()).setGuid(player.getGuid()).setUsername(player.getUsername()).build()).build();
            SendPrivateChat sendPrivateChat = new SendPrivateChat(ctx,player.getId(),clientChannelId);
            DbHandler.dbQueue.loadTask(sendPrivateChat);
        }
        ctx.writeAndFlush(loginDbMsg);
    }

}
